package com.ibm.moa.outmail.utils;

import java.io.ByteArrayInputStream;
import java.io.Closeable;
import java.io.File;
import java.io.InputStream;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import android.annotation.SuppressLint;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Color;
import android.graphics.drawable.GradientDrawable;
import android.graphics.drawable.StateListDrawable;
import android.net.Uri;
import android.text.TextUtils;
import android.text.TextUtils.TruncateAt;
import android.util.Log;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.ibm.moa.outmail.MailActivity;
import com.ibm.moa.outmail.R;
import com.ibm.moa.outmail.module.MailInfo;
import com.ibm.moa.outmail.view.FlowLayout;

public class Utils {
	public static String AUTHORITY = "com.ibm.moa.bmcc.portal";
	public static String[] messages;
	// 所有时间的标题
	private static final String[] titles = { "今天", "昨天", "一周内", "一周前", "两周前", "三周前", "一个月前", "两个月前", "更早 " };

	/**
	 * 加载等待提示(Dialog)
	 */
	public static Dialog createProgressDialog(Context context, String msg) {
		return ZProgressDialog.createProgressDialog(context, msg);
	}

	public static boolean matchMail(String str) {
		String cchar = "^\\w+@(\\w+.)+\\w+$";
		Pattern p = Pattern.compile(cchar);
		Matcher m = p.matcher(str);
		return m.matches();
	}

	public static boolean parseBoolean(String value) {
		boolean result = false;
		try {
			result = Boolean.parseBoolean(value);
		} catch (Exception e) {
		}
		return result;
	}

	public static int parseInt(String value) {
		int result = 0;
		try {
			result = Integer.parseInt(value);
		} catch (Exception e) {
		}
		return result;
	}

	/**
	 * 获取平台中提示语
	 * 
	 * @param context
	 * @param msg
	 * @return
	 */
	public static String getLoadingMessage(Context context, String msg) {
		try {
			Random random = new Random();
			if (messages != null && messages.length > 0) {
				msg = messages[random.nextInt(messages.length)];
			} else {
				Uri uri = Uri.parse("content://" + AUTHORITY + "/hint");
				Cursor c = context.getContentResolver().query(uri, new String[] { "message" }, null, null, null);
				if (c != null) {
					int max = c.getCount();
					if (max > 0) {
						messages = new String[max];
						int i = 0;
						Log.i("lgs", "max" + max);
						while (c.moveToNext()) {
							messages[i] = c.getString(0) + "";
							i++;
						}
						msg = messages[random.nextInt(messages.length)];
					}
					c.close();
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return msg;
	}

	public static void deleteDirectory(String currentDir) {
		try {
			File file = new File(currentDir);
			if (file.exists()) {
				if (!file.isDirectory()) {
					file.delete();
				} else if (file.isDirectory()) {
					File[] filelist = file.listFiles();
					for (File delfile : filelist) {
						if (delfile != null) {
							if (!delfile.isDirectory()) {
								delfile.delete();
							} else if (delfile.isDirectory()) {
								deleteDirectory(delfile.toString());
							}
						}
					}
					file.delete();
				}
			}
		} catch (Exception e) {
		}

	}

	/**
	 * 在一行显示多条文本
	 * 
	 * @param context
	 * @param recommendedKeywords
	 *            要显示的文本内容的数组
	 * @return View对象
	 */
	public static View getView(final Context context, String[] recommendedKeywords) {
		int backColor = 0xff257020;
		int color = 0xff399834;
		// 创建背景图片选择器
		int radius = (int) DensityUtil.dip2px(context, 13);
		// 初始化FlowLayout布局，该布局可以自动分配子View位置，保持每一行都能对齐
		FlowLayout mLayout = new FlowLayout(context);
		ViewGroup.LayoutParams params = new ViewGroup.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
		mLayout.setLayoutParams(params);

		// int layoutPaddingLeftRight = (int) DensityUtil.dip2px(context, 10);
		// int layoutPaddingTopBottom = (int) DensityUtil.dip2px(context, 2);
		// mLayout.setPadding(layoutPaddingLeftRight, layoutPaddingTopBottom,
		// layoutPaddingLeftRight, layoutPaddingTopBottom);
		mLayout.setHorizontalSpacing((int) DensityUtil.dip2px(context, 5));
		mLayout.setVerticalSpacing((int) DensityUtil.dip2px(context, 2));

		// int textPaddingV = (int) DensityUtil.dip2px(context, 2);
		int textPaddingH = (int) DensityUtil.dip2px(context, 10);

		for (int i = 0; i < recommendedKeywords.length; i++) {
			TextView tv = new TextView(context);
			GradientDrawable pressDrawable = DrawableUtils.createDrawable(backColor, backColor, radius);
			GradientDrawable normalDrawable = DrawableUtils.createDrawable(color, backColor, radius);
			// 代码动态创建一个图片
			StateListDrawable selector = DrawableUtils.createSelector(normalDrawable, pressDrawable);
			tv.setBackgroundDrawable(selector);

			final String text = recommendedKeywords[i];
			tv.setText(text);
			tv.setTextColor(Color.WHITE);
			tv.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 16);
			tv.setGravity(Gravity.CENTER);
			tv.setPadding(textPaddingH, 0, textPaddingH, 0);
			// tv.setMaxWidth(DensityUtil.dip2px(context, 100));
			tv.setSingleLine(true);
			tv.setEllipsize(TruncateAt.END);
			tv.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View v) {
					if (!TextUtils.isEmpty(text)) {
						Intent intent = new Intent(context, MailActivity.class);
						intent.putExtra("mailType", 4);
						intent.putExtra("receiveName", text);
						context.startActivity(intent);
					} else {
						Toast.makeText(context, "请选择一个发件人", Toast.LENGTH_SHORT).show();
					}
				}
			});
			mLayout.addView(tv);
		}

		return mLayout;
	}

	/**
	 * 根据给定的日期，返回该日期所在的日期数组中的索引 日期数组样式为：{"今天", "昨天", "一周内", "一周前", "两周前", "三周前", "一个月前", "两个月前", "更早 "}
	 * 
	 * @param beforeDate
	 *            需要查看的日期
	 * @return 返回该日期所在的日期数组中的索引
	 */
	@SuppressLint("SimpleDateFormat")
	public static int indexInDateArray(String beforeDate) {
		try {
			Date oldDate = new SimpleDateFormat("yyyy-MM-dd").parse(beforeDate);
			Date curDate = new Date();

			long days = (curDate.getTime() - oldDate.getTime()) / 1000 / 3600 / 24;

			if (days < 1) {// 今天
				return 0;
			} else if (days < 2) {// 昨天
				return 1;
			} else if (days < 7) {// 一周内
				return 2;
			} else if (days < 14) {// 一周前
				return 3;
			} else if (days < 21) {// 两周前
				return 4;
			} else if (days < 28) {// 三周前
				return 5;
			} else if (days < 60) {// 一个月前
				return 6;
			} else if (days < 90) {// 两个月前
				return 7;
			} else {// 更早
				return 8;
			}
		} catch (ParseException e) {
			e.printStackTrace();
		}

		return -1;
	}

	public static void setFujianIcon(ImageView fujianIcon, String fujianStr) {
		int lastIndex = fujianStr.lastIndexOf(".");
		if (lastIndex != -1 && lastIndex < fujianStr.length()) {
			String fileType = fujianStr.substring(lastIndex + 1).toLowerCase();
			if ("doc".equals(fileType) || "docx".equals(fileType)) {
				fujianIcon.setImageResource(R.drawable.w);
			} else if ("xls".equals(fileType) || "xlsx".equals(fileType)) {
				fujianIcon.setImageResource(R.drawable.x);
			} else if ("ppt".equals(fileType) || "pptx".equals(fileType)) {
				fujianIcon.setImageResource(R.drawable.ppt);
			} else if ("pdf".equals(fileType)) {
				fujianIcon.setImageResource(R.drawable.pdf);
			} else if ("txt".equals(fileType)) {
				fujianIcon.setImageResource(R.drawable.txt);
			} else if ("rar".equals(fileType) || "zip".equals(fileType)) {
				fujianIcon.setImageResource(R.drawable.zip);
			} else if ("jpg".equals(fileType) || "png".equals(fileType) || "gif".equals(fileType) || "jpeg".equals(fileType)) {
				fujianIcon.setImageResource(R.drawable.jpg);
			} else {
				fujianIcon.setImageResource(R.drawable.fujian_icon);
			}
		} else {
			fujianIcon.setImageResource(R.drawable.fujian_icon);
		}
	}

	/**
	 * 将临时的List集合中的数据拷贝到Map集合中
	 */
	public static void copyMailList2MailMap(ArrayList<MailInfo> tempMailInfoList, Map<Integer, List<MailInfo>> mailInfoMap, List<String> timeTitles) {
		for (int i = 0; i < tempMailInfoList.size(); i++) {

			MailInfo mailInfo = tempMailInfoList.get(i);
			if (null != mailInfo && null != mailInfo.sendDate) {
				int index = Utils.indexInDateArray(mailInfo.sendDate);

				if (-1 != index) {
					if (!mailInfoMap.containsKey(index)) {
						mailInfoMap.put(index, new ArrayList<MailInfo>());
					}

					mailInfoMap.get(index).add(mailInfo);
				}
			}
		}
		tempMailInfoList.clear();

		// 获取所有的标题，放到标题集合中
		if (mailInfoMap.size() > 0) {
			timeTitles.clear();

			Set<Integer> titleSet = mailInfoMap.keySet();

			for (Integer i : titleSet) {
				timeTitles.add(titles[i]);
			}
		}
	}

	/**
	 * 获取指定Map<Integer, List<MailInfo>>集合的总共的记录数量
	 * 
	 * @param map
	 *            需要获取的集合
	 * @return 总记录数
	 */
	public static int getMapSize(Map<Integer, List<MailInfo>> map) {
		int result = 0;

		for (List<MailInfo> list : map.values()) {
			result += list.size();
		}

		return result;
	}

	/**
	 * 将XML转换成MAP结构
	 * 
	 * @param xml
	 * @return
	 * @throws ParseException
	 * @throws Exception
	 */
	public static HashMap xmlToMap(String xml) throws ParseException, Exception {

		// xml=URLDecoder.decode(xml,"UTF-8");
		if (xml != null) {
			xml = xml.replaceAll("&#", "##");
		}
		HashMap<String, String> result = new HashMap<String, String>();
		byte[] tagetXml = xml.getBytes("utf-8");
		InputStream in = new ByteArrayInputStream(tagetXml);
		// InputStreamReader utf8In = new InputStreamReader(in, "utf-8");
		DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
		try {
			DocumentBuilder builder = factory.newDocumentBuilder();
			Document dom = builder.parse(in);
			Element root = dom.getDocumentElement();
			NodeList nodeList = root.getElementsByTagName("property");
			int len = nodeList.getLength();
			for (int i = 0; i < len; i++) {
				Node node = nodeList.item(i);
				if (node.getNodeType() == Element.ELEMENT_NODE) {
					Element emlt = (Element) node;
					result.put(emlt.getAttribute("name"), emlt.getNodeValue());
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			closeIO(in);
		}

		return result;
	}

	public static void closeIO(Closeable closeable) {
		if (closeable != null) {
			try {
				closeable.close();
			} catch (Exception e) {
			}
			closeable = null;
		}
	}
}
